<?php

class Post{
    private $response;
    private $data; //dados
    private $curl;
    private $url;

    public function __construct($data=null, $url=null, $port=null, $query=null) {
        if($url == null) $url = PUBLIC_ROOT_.'/notificator.php';
        if($query === true) $data = http_build_query($data);
       
        $this->url = $url;
        $this->data = $data;

        $cURL = curl_init();
        curl_setopt($cURL, CURLOPT_URL, $this->url);
        curl_setopt($cURL, CURLOPT_POST, true);
        if($data != null) curl_setopt($cURL, CURLOPT_POSTFIELDS, $data);
        curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

        $this->curl = $cURL;

        if($port != null) $this->setPort($port);
    }

    public function setProperties($data, $url=null){
        if(is_array($data)){
            $params = $data;
            foreach($params as $key => $value) $this->$key = $value;    
        }else{
            $this->data = $data;
            $this->url = $url;
        }        
    }

    public function setUrl($url){
        $this->url = $url;

        curl_setopt($this->curl,CURLOPT_URL,$url);
    }

    public function setPort($port){
        $arrayUrl = parse_url($this->url); //quebra num array associativo com o parse_url
        $url = $arrayUrl['scheme'].'://'.$arrayUrl['host'].':'.$port.$arrayUrl['path']; //adiciona a port no meio
       

        $this->setUrl($url);
    }

    public function send(){
        $this->response = curl_exec($this->curl);
    }

    public function setData($data){
        $this->data = $data;
       
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data);
    }

    public function getResponse(){
        echo $this->response;
        return json_decode($this->response);
    }

    public function setOption($option, $value){
        curl_setopt($this->curl, $option, $value);
    }

    public function __destruct() {
        curl_close($this->curl);
    }
}
?>